<template>
  <div class="flex flex-1 h-full w-full justify-center items-center overflow-x-auto relative">
    <a-card :bordered="false" :body-style="{ padding: 0 }" class="absolute top-4 w-[90%] head z-10">
      <div class="w-full h-full px-8 flex justify-between items-center">
        <div class="font-bold text-[1.5rem]">LCD下发</div>
        <a-button
          type="primary"
          @click="send"
          :disabled="!lcdDistribution.themeId || !lcdDistribution.mediaId"
        >
          {{ t('下发') }}
        </a-button>
      </div>
    </a-card>
    <ThemeEditor
      v-if="currentTheme"
      v-model:value="currentComponent"
      v-model:scale="currentTheme.scale"
      :data="currentTheme.image"
      :width="currentTheme.width!"
      :height="currentTheme.height!"
      :background="currentTheme.background"
      @select="onSelect"
      @click-stage="onStage"
    />
    <div v-else class="empty w-full h-full p-4 flex justify-center items-center">
      <a-empty />
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ThemeCanvas } from '@/types/theme';
import {
  componentList,
  currentComponent,
  currentTheme,
  distributionTab,
  lcdDistribution,
} from '../data/data';
import { boundMedia } from '@/api/modules/lcd/lcd-device';
import { previewTheme } from '@/api/modules/lcd/theme';
import { notify } from '@/utils/common/common';

const { t } = useI18n();
const send = async () => {
  const config = {
    // 当前选中的模板 ID
    themeId: lcdDistribution.value.themeId,
    // 表单中的媒体 ID
    mediaId: lcdDistribution.value.mediaId,
    // 组件列表
    goodsList: componentList.value
      .map(e => {
        let productId = e.productIds[0];
        if (productId) {
          return productId;
        }
        return '';
      })
      .filter(e => !!e),
  };
  const { data } = await boundMedia(config);
  notify(data);
};
const onSelect = (item: ThemeCanvas) => {
  currentComponent.value = item;
  lcdDistribution.value.currentProductId = item.productIds[0];
  distributionTab.value = 'product';
};

const onStage = () => {
  distributionTab.value = 'theme';
};
const preview = async () => {
  if (
    lcdDistribution.value.themeId &&
    lcdDistribution.value.currentProductId &&
    currentComponent.value.id
  ) {
    const { data } = await previewTheme(
      lcdDistribution.value.currentProductId,
      currentComponent.value.templateId,
    );
    currentComponent.value.imageSrc = data.data;
  }
};
watch(
  lcdDistribution,
  () => {
    preview();
  },
  {
    deep: true,
    immediate: true,
  },
);
</script>

<style lang="scss" scoped>
.empty {
  background: var(--background-color);
}
.head {
  line-height: 48px;
  height: 48px;
  border-radius: 12px !important;
}
</style>
